package com.dongdong.service.impl;

import com.alibaba.fastjson.JSON;
import com.dongdong.api.CartAPI;
import com.dongdong.api.ItemAPI;
import com.dongdong.api.UserAPI;
import com.dongdong.em.Result;
import com.dongdong.mapper.TbOrderItemMapper;
import com.dongdong.mapper.TbOrderMapper;
import com.dongdong.model.*;
import com.dongdong.service.OrderItemService;
import com.dongdong.service.OrderService;
import com.dongdong.util.IdWorker;
import com.dongdong.util.JWTUtil;
import com.dongdong.vo.*;
import io.jsonwebtoken.Claims;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private TbOrderMapper orderMapper;

    @Autowired
    private CartAPI cartAPI;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private JWTUtil jwtUtil;

    @Autowired
    private UserAPI userAPI;

    @Autowired
    private TbOrderItemMapper orderItemMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ItemAPI itemAPI;

    @Autowired
    private OrderItemService orderItemService;

    @Override
    @Transactional     //只能控制单体事务   如果想要控制其他服务 那就要使用到事物的传播特性
//    @GlobalTransactional(rollbackFor = Exception.class)    //添加全局事务注解
    public AliPayVO submitOrder(String autherizetion, Long addressId, String paymentType) {
        //获取购物车
        Result<List<CartVO>> resultCartVOList = cartAPI.GetCart(autherizetion);
        List<CartVO> redisCart = resultCartVOList.getData();


        //解析用户token
        Claims claims = jwtUtil.parseJwt(autherizetion);
        String subject = claims.getSubject();
        String userid1 = claims.getId();
        TbUser user = JSON.parseObject(subject, TbUser.class);

        //根据地址表id 查询全部
        Result<AddressVO> addressVOResult = userAPI.getAddressById(addressId);
        AddressVO addressVO = addressVOResult.getData();

        //定义两个集合 - 批量增加
        ArrayList<TbOrder> orders = new ArrayList<>();
        ArrayList<TbOrderItem> orderItems = new ArrayList<>();

        //定义一个扣减库存的集合
        ArrayList<TbItem> kc = new ArrayList<>();


        //定义总金额
        BigDecimal total_amount = new BigDecimal(0);

        //定义StringBuider  拼接标题
        StringBuilder builder = new StringBuilder();

        //定义支付记录表 id
        long l = idWorker.nextId();

        for (CartVO cartVO : redisCart) {
            TbOrder order = new TbOrder();
            order.setOrderId(idWorker.nextId());
            order.setPaymentType(paymentType);
            order.setStatus("1");
            order.setCreateTime(new Date());
            order.setUpdateTime(new Date());
            order.setUserId(user.getUsername());
            order.setReceiverAreaName(addressVO.getAddress());
            order.setReceiverMobile(addressVO.getMobile());
            order.setReceiver(addressVO.getContact());
            order.setSellerId(cartVO.getSeller());
            order.setOrderNo(String.valueOf(l));


            //定义实付金额
            BigDecimal sum = new BigDecimal(0);

            //组装订单明细
            List<DetailVO> detailVOS = cartVO.getDetailVOS();
            for (DetailVO detailVO : detailVOS) {
                //创建订单明细对象
                TbOrderItem orderItem = new TbOrderItem();
                orderItem.setId(idWorker.nextId());
                orderItem.setItemId(detailVO.getSkuid());
                orderItem.setGoodsId(detailVO.getGoodsId());
                orderItem.setOrderId(order.getOrderId());
                orderItem.setTitle(detailVO.getTitle());
                orderItem.setNum(detailVO.getNum());
                orderItem.setPrice(detailVO.getPrice());
                orderItem.setTotalFee(detailVO.getTotalFee());
                orderItem.setPicPath(detailVO.getPicPath());
                orderItem.setSellerId(order.getSellerId());
                orderItem.setOrderNo(String.valueOf(l));
                sum = sum.add(orderItem.getTotalFee());
                total_amount = total_amount.add(orderItem.getTotalFee());
                builder = builder.append(detailVO.getTitle());

                //扣减库存的数据
                TbItem tbItem = new TbItem();
                tbItem.setId(detailVO.getSkuid());
                tbItem.setNum(detailVO.getNum());
                kc.add(tbItem);


                //放进集合  防止循环增加
                orderItems.add(orderItem);
            }
            //设置实付金额
            order.setPayment(sum);
            orders.add(order);
        }

        //扣减库存
        itemAPI.subStockCount(kc);//扣减库存

        //调用批量增加方法  增加订单和订单明细
        orderMapper.insertOrderBatch(orders);
//        int i = 0 / 9;//由于添加了seata控制  所以只要上面的操作执行成功  就算这里有异常也会回滚  执行成功  保证原子性
        orderItemMapper.insertOrderItemBatch(orderItems);

        //清空购物车
//        Boolean cartList = redisTemplate.delete("cartList");
        Long cartList = redisTemplate.boundHashOps("cartList").delete(userid1);//根据id存储的时候是string类型   转成对象之后是long类型
        System.out.println(cartList);

        //将参数封装进AliPayVO
        AliPayVO payVO = new AliPayVO();
        payVO.setOut_trade_no(String.valueOf(l));
        payVO.setTotal_amount(total_amount);
        payVO.setSubject(builder.toString());
        return payVO;
    }


    @Override
    public List<OrderVO> getOrderByUserId(String userid) {
        TbOrderExample example = new TbOrderExample();
        example.createCriteria().andUserIdEqualTo(userid);

        List<TbOrder> tbOrders = orderMapper.selectByExample(example);

        List<OrderVO> collect = tbOrders.stream().map(orderlist -> {
            OrderVO vo = new OrderVO();
            BeanUtils.copyProperties(orderlist, vo);
            return vo;
        }).collect(Collectors.toList());

        for (OrderVO orderVO : collect) {
            List<OrderItemVO> orderItemList = new ArrayList<>();
            Long orderId = orderVO.getOrderId();
            //1.根据orderid 查询item的orderid  匹配   根据订单编号分类（根据商家的逻辑分类）  把查询到的item放进itemVO
            List<OrderItemVO> orderItemVOS = orderItemService.getOrderIdByOrderItemOrderId(orderId);
            for (OrderItemVO orderItemVO : orderItemVOS) {
                //2.然后根据商家分类的逻辑  判断order表和orderitem的订单编号  如果一直就加入一个集合   如果不一致就重新循环加入一个新的集合
                if (Objects.equals(orderVO.getOrderNo(), orderItemVO.getOrderNo())) {
                    orderItemList.add(orderItemVO);
                }
            }
            //3.将拿到的orderitem  set进ordervo的orderitemvos中
            orderVO.setOrderItemVOS(orderItemList);
        }
        return collect;
    }

    @Override
    public int getOrderNoUpSatus(String trade_no) {//付款成功  增加流水号  同时修改order表的状态为2 已付款
        //先通过订单编号 查询出数据  然后修改状态为2
        TbOrderExample example = new TbOrderExample();
        example.createCriteria().andOrderNoEqualTo(trade_no);

        List<TbOrder> tbOrders = orderMapper.selectByExample(example);

        for (TbOrder tbOrder : tbOrders) {
            tbOrder.setStatus("2");

            int i = orderMapper.updateByPrimaryKeySelective(tbOrder);
            return i;
        }
        return 0;
    }
}
